package com.qlogic.commons.utils.os;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class OsCommandExecuterThread extends Thread {

	private OsCommandExecuter executer;
	private String command;
	private int type;
	private InputStream is;
	
	public OsCommandExecuterThread (OsCommandExecuter executer, String command, int type, InputStream is) {
		this.executer = executer;
		this.command = command;
		this.type = type;
		this.is = is;
	}
	
	public void run () {
		OsCommandResult osCommandResult = createOsCommandResult ();
		executer.setSingleShellResult (osCommandResult);
		// must be in thread
		if (!executer.isSingleShell ()) {
			executer.addResult (command, osCommandResult);
		}
	}
	
	private OsCommandResult createOsCommandResult () {
		OsCommandResult osCommandResult = executer.getResult (command);
		if (osCommandResult != null && osCommandResult.getType () == OsCommandResult.ERROR) {
			return osCommandResult;
		}
		osCommandResult = new OsCommandResult (type);
		InputStreamReader isr = new InputStreamReader(is);
		BufferedReader br = new BufferedReader(isr);
		String line = null;
		try {
			while ((line = br.readLine()) != null) {
				osCommandResult.addRow (line);
			}
		} catch (IOException e) {
			e.printStackTrace ();
		}
		
		if (osCommandResult.getRowsCount () == 0) {
			if (type == OsCommandResult.ERROR) {
				osCommandResult.addRow ("Command [" + command + "] executed with errors");
			} else {
				osCommandResult.addRow ("Command [" + command + "] executed with success");
			}
			osCommandResult.setNoOsResult (true);
		}
		return osCommandResult;
	}
}
